package com.sunlee.admin.api.module.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sunlee.common.core.constant.Constant;
import com.sunlee.common.core.entity.PageData;
import com.sunlee.common.core.entity.Result;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.service.dto.ThirdCategoryDTO;
import com.sunlee.common.service.dto.ThirdProductDTO;
import com.sunlee.common.service.entity.ThirdCategoryEntity;
import com.sunlee.common.service.entity.ThirdProductCategoryMappingEntity;
import com.sunlee.common.service.entity.ThirdProductEntity;
import com.sunlee.common.service.service.ThirdCategoryService;
import com.sunlee.common.service.service.ThirdProductCategoryMappingService;
import com.sunlee.common.service.service.ThirdProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;
import java.util.Objects;

/**
 * @author sunjulei
 * @date 2023/3/7
 */
@RestController
@RequestMapping("third/productCategory")
@Api(tags = "第三方商品分类映射表")
public class ThirdProductCategoryController {

    @Autowired
    private ThirdProductCategoryMappingService service;
    @Autowired
    private ThirdProductService thirdProductService;
    @Autowired
    private ThirdCategoryService thirdCategoryService;

    /**
     * 通过商品ID分页查询分类关联情况
     */
    @GetMapping("/pageByPid")
    @ApiOperation("分页")
    @RequiresPermissions("third:product:page")
    public Result<PageData<ThirdCategoryDTO>> pageByPid(@ApiIgnore @RequestParam Map<String, Object> params) {
        long pid = Long.parseLong((String) params.getOrDefault(Constant.PID, "0"));
        if (pid <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }
        return Result.ok(service.pageRelatedByPid(params, pid));
    }

    /**
     * 通过商品Id关联多个分类
     */
    @PostMapping("/editByPid/{productId}")
    @ApiOperation("编辑")
    @RequiresPermissions("third:product:save")
    public Result<Object> editByPid(@PathVariable("productId") Long productId,
                                    @RequestBody Long[] cIds) {
        if (productId == null || productId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }
        service.editByPid(productId, cIds);
        return Result.ok();
    }

    /**
     * 通过商品Id，添加分类关联
     */
    @PostMapping("/saveByPid/{productId}/{categoryId}")
    @ApiOperation("编辑")
    @RequiresPermissions("third:product:save")
    public Result<Object> saveByPid(@PathVariable("productId") Long productId,
                                    @PathVariable("categoryId") Long categoryId) {

        if (productId == null || productId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }
        if (categoryId == null || categoryId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }

        ThirdCategoryEntity category = thirdCategoryService.getById(categoryId);
        if (Objects.isNull(category)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该资源ID：" + categoryId));
        }

        ThirdProductEntity product = thirdProductService.getById(productId);
        if (Objects.isNull(product)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该商品ID：" + productId));
        }

        ThirdProductCategoryMappingEntity entity = new ThirdProductCategoryMappingEntity();
        entity.setSource(product.getSource());
        entity.setProductId(productId);
        entity.setCategoryId(categoryId);

        service.save(entity);
        return Result.ok();
    }

    /**
     * 通过商品Id，删除分类关联
     */
    @PostMapping("/deleteByPid/{productId}/{categoryId}")
    @ApiOperation("编辑")
    @RequiresPermissions("third:product:delete")
    public Result<Object> deleteByPid(@PathVariable("productId") Long productId,
                                      @PathVariable("categoryId") Long categoryId) {

        if (productId == null || productId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }
        if (categoryId == null || categoryId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }

        ThirdCategoryEntity category = thirdCategoryService.getById(categoryId);
        if (Objects.isNull(category)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该资源ID：" + categoryId));
        }

        ThirdProductEntity product = thirdProductService.getById(productId);
        if (Objects.isNull(product)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该商品ID：" + productId));
        }

        service.remove(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .eq(ThirdProductCategoryMappingEntity::getSource, product.getSource())
                .eq(ThirdProductCategoryMappingEntity::getProductId, productId)
                .eq(ThirdProductCategoryMappingEntity::getCategoryId, categoryId));

        return Result.ok();
    }

    /**
     * 通过分类ID分页查询可关联 或 已关联商品
     */
    @GetMapping("/pageByCid")
    @ApiOperation("分页")
    @RequiresPermissions("third:product:page")
    public Result<PageData<ThirdProductDTO>> pageByCid(@ApiIgnore @RequestParam Map<String, Object> params) {

        long cId = Long.parseLong((String) params.getOrDefault(Constant.ID, "0"));
        if (cId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }

        return Result.ok(service.pageRelatedByCid(params, cId));
    }
}
